package netty.udp.demo2;

import cn.hutool.core.util.CharsetUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @program JavaBase
 * @description: 日志事件客户端监控
 * @author: zhanglu
 * @create: 2020-07-01 15:31:00
 */
@Slf4j
public class LogEventMonitor {

    private final Bootstrap bootstrap;
    private final EventLoopGroup group;
    private Integer port;

    public LogEventMonitor(Integer port) {
        this.group = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        this.port = port;
        this.bootstrap.group(this.group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<Channel>() {    //多个处理器
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new LogEventDecoder());
                        pipeline.addLast(new LogEventHandle(port));
                    }
                });
    }

    public Channel bind() {
        return this.bootstrap.bind(port).syncUninterruptibly().channel();  //3
    }

    public void stop() {
        this.group.shutdownGracefully();
    }


    /**
     * 接收数据前，先解码
     */
    private class LogEventDecoder extends MessageToMessageDecoder<DatagramPacket> {
        @Override
        protected void decode(ChannelHandlerContext ctx, DatagramPacket datagramPacket, List<Object> out) throws Exception {
            //获取内容
            ByteBuf byteBuf = datagramPacket.copy().content();
            String msg = byteBuf.toString(CharsetUtil.charset(CharsetUtil.UTF_8));
            out.add(msg);
        }
    }

    private class LogEventHandle extends SimpleChannelInboundHandler<String>{

        private final Integer port;

        private LogEventHandle(Integer port) {
            this.port = port;
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            log.info("客户端["+port+"]接收：" + msg);
        }

    }

    public static void main(String[] args) {
        for (Integer port : LogEventBroadcaster.clientList) {
            Runnable r = () -> {
                log.info("客户端启动～" + port);
                LogEventMonitor logEventMonitor = new LogEventMonitor(port);
                try {
                    Channel channel = logEventMonitor.bind();
                    channel.closeFuture().await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    logEventMonitor.stop();
                }
            };
            new Thread(r).start();
        }


    }

}
